<?php

namespace app\api\controller\User;

use app\services\UserCouponService;
use support\Db;
use support\Request;

class CouponController
{
    public function orderCanUseList(Request $request)
    {
        try {
            $cartItemIds = $request->post('cart_item_ids');

            if (empty($cartItemIds)) {
                throw new \Exception('请传入购物车项ID');
            }

            UserCouponService::getOrderCouponList($cartItemIds);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function receiveRegisterCoupons(Request $request)
    {
        try {
            Db::beginTransaction();

            UserCouponService::receiveRegisterSendCoupons();

            Db::commit();

            return ok_rsp('成功');
        } catch (\Exception $e) {
            Db::rollBack();
            return err_rsp($e->getMessage());
        }
    }

    public function receive(Request $request)
    {
        try {
            Db::beginTransaction();
            $id = $request->post('coupon_id');

            UserCouponService::give($id, get_user_id(), true);

            Db::commit();

            return ok_rsp('成功');
        } catch (\Exception $e) {
            Db::rollBack();
            return err_rsp($e->getMessage());
        }
    }

    public function list(Request $request)
    {
        try {
            $page = $request->post('page', 1);
            $length = $request->post('length', 10);
            $type = $request->post('type', 0);

            $data = UserCouponService::list($page, $length, $type);
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            Db::rollBack();
            return err_rsp($e->getMessage());
        }
    }
}